<?php
/*------------------------------------------------------------------------
# com_vportfolio - Vportfolio component
# ------------------------------------------------------------------------
# author    Vsmart Extensions
# copyright Copyright (C) 2010 www.vsmart-extensions.com. All Rights Reserved.
# @license - http://www.gnu.org/licenses/gpl-2.0.html GNU/GPL
# Websites: http://www.vsmart-extensions.com
# Technical Support:  Forum - http://www.vsmart-extensions.com
-------------------------------------------------------------------------*/
// no direct access
defined( '_JEXEC' ) or die( 'Restricted access' );

jimport( 'joomla.application.component.model' );

/**
 * @package Joomla
 * @subpackage Vportfolio
 */
class vportfolioComponentModel extends JModel
{
	/** @var object JTable object */
	var $_table = '#__vportfolio';
	var $lists;
	var $items;
	var $pagination;

	/**
	 * Returns the internal table object
	 * @return JTable
	 */
	function &getTable()
	{
		if ($this->_table == null) {
			$this->_table = JTable::getInstance('component', $this->getDBO() );
		}
		return $this->_table;
	}
	function &getListItem(){
		global $mainframe, $option;
		
		$db =& JFactory::getDBO();
		$search				= $mainframe->getUserStateFromRequest( "$option.search",			'search', 			'',			'string' );
		$filter_category	= $mainframe->getUserStateFromRequest( "$option.filter_category",	'filter_category', 		0,			'string' );
		$search				= JString::strtolower( $search );

		$limit		= $mainframe->getUserStateFromRequest( 'global.list.limit', 'limit', $mainframe->getCfg('list_limit'), 'int' );
		$limitstart = $mainframe->getUserStateFromRequest( $option.'.limitstart', 'limitstart', 0, 'int' );

		$where = array();
		if (isset( $search ) && $search!= '')
		{
			$searchEscaped = $db->Quote( '%'.$db->getEscaped( $search, true ).'%', false );
			$where[] = 'a.title LIKE '.$searchEscaped.' OR a.description LIKE '.$searchEscaped;
		}
		
		if ( $filter_category )
		{
			$where[] = ' a.categoryId = \''.$filter_category.'\'';
		}

		$where = ( count( $where ) ? ' WHERE (' . implode( ') AND (', $where ) . ')' : '' );

		$query = 'SELECT COUNT(a.id)'
		. ' FROM #__vportfolio AS a'
		. $where
		;
		$db->setQuery( $query );
		$total = $db->loadResult();

		jimport('joomla.html.pagination');
		$pagination = new JPagination( $total, $limitstart, $limit );
		
		$query = 'SELECT a.* '
			. ' FROM #__vportfolio AS a'
			. $where
		;
		$db->setQuery( $query, $pagination->limitstart, $pagination->limit );
		$rows = $db->loadObjectList();
		
		$lists['search']= $search;
		
		$query = 'SELECT a.id AS value, a.name AS text '
		. ' FROM #__vportfolio_category AS a'
		. ' ORDER BY a.id'
		;

		$db->setQuery( $query );
		
		$types[] 		= JHTML::_('select.option',  '0', '- '. JText::_( 'Select Category' ) .' -' );
		foreach( $db->loadObjectList() as $obj )
		{
			$types[] = JHTML::_('select.option',  $obj->value, JText::_( $obj->text ) );
		}
		$lists['category'] 	= JHTML::_('select.genericlist',   $types, 'filter_category', 'class="inputbox" size="1" onchange="document.adminForm.submit( );"', 'value', 'text', "$filter_category" );
		

		$this->lists = $lists;
		
		$this->items = $rows;
		
		$this->pagination = $pagination;
		
		//Get thumbnail
		for($i=0;$i<sizeof($this->items);$i++){
			$images = $this->getImages($this->items[$i]->id);
			$this->items[$i]->image = $images[0];
		}
	}
	function &getItem($id=0){
	
		$cid		= JRequest::getVar( 'cid', array(0), '', 'array' );
		if($cid[0] =="")
			$cid[0] = $id;
		$edit		= JRequest::getVar('edit',true);
		JArrayHelper::toInteger($cid, array(0));
		
		$db 		=& JFactory::getDBO();
		
		$query = 'SELECT * FROM #__vportfolio WHERE id="'.$cid[0].'"';
		$db->setQuery($query);
		$rows = $db->loadObjectList();
		$row = $rows[0];
		$row->images = $this->getImages($row->id);
		$row->reviews = $this->getReviews($row->id);
		$row->rating = $this->getRatings($row->id);
		return $row;
	}
	function &saveItem(){
		global $mainframe;
		
		$option = JRequest::getCmd( 'option');
		$id		= JRequest::getVar('id',0);
		//Save data
		$post = JRequest::get('post');
		$post['description'] = JRequest::getVar('description', '', 'post', 'string', JREQUEST_ALLOWRAW);
		$post['fulldescription'] = JRequest::getVar('fulldescription', '', 'post', 'string', JREQUEST_ALLOWRAW);
		
		$item = new VSTItem($id);
		
		if (!$item->bind($post)){
			return false;
		}
		$currentId = $item->save();
		return $currentId;
	}
	function &getImages($id){
	
		$db 		=& JFactory::getDBO();
		$query = 'SELECT * FROM #__vportfolio_image WHERE itemId="'.$id.'" ORDER BY `default` DESC, id ASC ';
		$db->setQuery($query);
		$images = $db->loadObjectList();
		if(count($images) > 0)
			return $images;
		else
			return 0;
	}
	
	function &getReviews($id){
	
		$db 		=& JFactory::getDBO();
		$query = 'SELECT * FROM #__vportfolio_review WHERE itemId="'.$id.'"';
		$db->setQuery($query);
		$reviews = $db->loadObjectList();
		if(count($reviews) > 0)
			return $reviews;
		else
			return 0;
	}
	function &getRatings($id){
	
		$db 		=& JFactory::getDBO();
		$query = 'SELECT * FROM #__vportfolio_rating WHERE itemId="'.$id.'"';
		$db->setQuery($query);
		$ratings = $db->loadObjectList();
		
		if(count($ratings) <= 0 )
			$rating = 0;
		else{
			$sum = 0;
			$num = count($ratings);
			for($i=0;$i<sizeof($ratings);$i++){
				$sum = $sum + $ratings[$i]->rating;
			}
			$rating = $sum/$num;
			$rating = round($rating);
		}
		
		return $rating;
	}
	function publicItem(){
		$row = $this->getItem();
		if($row->public == 1) $row->public = 0;
		else $row->public = 1;
		$db 		=& JFactory::getDBO();
		$sql = "UPDATE #__vportfolio SET ".
					"public = '".$row->public."'".
					" WHERE id = '".$row->id."'";
		$db->setQuery($sql);
		$return = $db->query();	
		return $return;
		
	}
	//----------
	/**
	 * Method to (un)publish  class
	 * @access	public
	 * @return	boolean	True on success
	 * @since	1.5
	 * $publish = 1 -> pub , $publish = 0 -> unpub
	 */
	function publish($cid = array(), $publish = 1)
	{
		if (count( $cid ))
		{					
			JArrayHelper::toInteger($cid);
			$cids = implode( ',', $cid );				
			$query = 'UPDATE #__vportfolio '
				. ' SET public = '.(int) $publish
				. ' WHERE id IN ( '.$cids.' )';
			$db =& JFactory::getDBO();
			$db->setQuery( $query );
			if (!$db->query()) {
				$this->setError($db->getErrorMsg());
				return false;
			}
		}
		return true;
	}		
	
	function deleteListItem(){
		$cid = JRequest::getVar( 'cid', array(0), '', 'array' );
		
		
		for($i=0;$i<sizeof($cid);$i++){
			$db 		=& JFactory::getDBO();
			$id = $cid[$i];
			
			$query = 'SELECT * FROM #__vportfolio WHERE id="'.$id.'"';
			$db->setQuery($query);
			$rows = $db->loadObjectList();
			$row = $rows[0];
			
			//start delete
		
			$sql = "DELETE FROM #__vportfolio WHERE id = '".$id."'";
			$db->setQuery($sql);
			$db->query();
			//delete image
			$sql = "DELETE FROM #__vportfolio_image WHERE itemId = '".$id."'";
			$db->setQuery($sql);
			$db->query();

			$directory = JPATH_SITE."/components/com_vportfolio/images/".$row->id;

			if( !$dirhandle = @opendir($directory) )
					return;

			while( false !== ($filename = readdir($dirhandle)) ) {
					if( $filename != "." && $filename != ".." ) {
						$filename = $directory. "/". $filename;
						@unlink($filename);
					}
			}
			closedir($dirhandle);
			rmdir($directory);
			
			//delete review
			$sql = "DELETE FROM #__vportfolio_review WHERE itemId = '".$id."'";
			$db->setQuery($sql);
			$db->query();
			//delete rating
			$sql = "DELETE FROM #__vportfolio_rating WHERE itemId = '".$id."'";
			$db->setQuery($sql);
			$db->query();
		}
		
	}
	function removeImage(){
		$id		= JRequest::getVar('id',0);
		$itemId = JRequest::getVar('itemId',0);
		
		$db 		=& JFactory::getDBO();
		
		$query = 'SELECT * FROM #__vportfolio WHERE id="'.$itemId.'"';
		$db->setQuery($query);
		$rows = $db->loadObjectList();
		$row = $rows[0];
		
		$query = 'SELECT imageName FROM #__vportfolio_image WHERE id="'.$id.'"';
		$db->setQuery($query);
		$imageName = $db->loadResult();
		
		$sql = "DELETE FROM #__vportfolio_image WHERE id = '".$id."'";
		$db->setQuery($sql);
		$db->query();

		$image_path = JPATH_SITE."/components/com_vportfolio/images/".$row->id."/".$imageName;
		@unlink($image_path);
		
		$this->reShowImages($row);
		
	}
	function &reShowImages($row){
	
		global $mainframe;
		
		$mosConfig_live_site = $mainframe->getSiteURL();
		
		$images = $this->getImages($row->id);
		
		$content = "";
		
		$image_folder = $mosConfig_live_site."components/com_vportfolio/images/".$row->id."/";
		
		for($i=0;$i<sizeof($images);$i++){
				$param = " alt=\"".$item->images[$i]->imageTitle."\"";
                
				$content .= '<div class="imageBorder">'.
				'<div class="imageBackground">'.
				'<span class="editlinktip hasTip" title="'.JText::_( 'Image Size' ).'::'.$images[$i]->imageSize.'">'.
				displayImage($image_folder.$images[$i]->imageName,125,125,$param).
				'</span></div><br />'.
				'<a href="#" onclick="deleteImage(\''.$images[$i]->id.'\')">Delete</a><input type="radio" class="defaultRadio" name="default" id="default" onclick="setDefault(\''.$images[$i]->id.'\')"';
						
				if($images[$i]->default == 1) $content .= ' "checked" />';
				
				$content .= '<a href="#">Set default</a>';
				$content .= '</div>';
         }
		echo $content;
	}
	function setImageDefault(){
		$id		= JRequest::getVar('id',0);
		$itemId = JRequest::getVar('itemId',0);
		$db 		=& JFactory::getDBO();
		
		$query = "UPDATE #__vportfolio_image SET `default` = 0 WHERE itemId = '".$itemId."'";
		$db->setQuery($query);
		$db->query();
		
		$query = "UPDATE #__vportfolio_image SET `default` = 1 WHERE id = '".$id."'";
		$db->setQuery($query);
		$db->query();
	}
	function saveReview(){
		$itemId = JRequest::getVar('itemId',0);
		
		if($itemId == 0){
			echo "ERROR: Please create Item first!";
			die();
		}
		$review = JRequest::getVar('review','');
		$customer = JRequest::getVar('customer','');
		
		$db 		=& JFactory::getDBO();
		
		$query = "INSERT INTO #__vportfolio_review SET `review` = '".mysql_escape_string($review)."', `customer`='".$customer."',  itemId = '".$itemId."'";
		$db->setQuery($query);
		$db->query();
		$reviewId = $db->insertid();
		
		echo "<p>".$review."</p>";
		echo "<b> - ".$customer." - </b>";
		echo ' <span class="spanLink" onclick="publicReview(\''.$reviewId.'\',\'1\')">Public</span>';
        echo '&nbsp;&nbsp;|&nbsp;&nbsp;<span class="spanLink" onclick="deleteReview(\''.$reviewId.'\')">Remove</span>';
	}
	function publicReview(){
		$id = JRequest::getVar('id',0);
		$public = JRequest::getVar('public', 0);
		
		$db 		=& JFactory::getDBO();
		
		$query = "UPDATE #__vportfolio_review SET `public` = '".$public."' WHERE id = '".$id."'";
		$db->setQuery($query);
		$db->query();
		
		$query = 'SELECT itemId FROM #__vportfolio_review WHERE id="'.$id.'"';
		$db->setQuery($query);
		$itemId = $db->loadResult();
		
		
		$this->reShowReview($itemId);
	}
	function removeReview(){
	
		$id = JRequest::getVar('id',0);
		
		$db 		=& JFactory::getDBO();
		
		$query = 'SELECT itemId FROM #__vportfolio_review WHERE id="'.$id.'"';
		$db->setQuery($query);
		
		$itemId = $db->loadResult();
		
		$query = "DELETE FROM #__vportfolio_review WHERE id = '".$id."'";
		$db->setQuery($query);
		$db->query();
		
		$this->reShowReview($itemId);
	}
	function &reShowReview($itemId){
		
		$reviews = $this->getReviews($itemId);
		
		if($reviews){
			for($i=0;$i<sizeof($reviews);$i++){
				echo "<p>".$reviews[$i]->review."</p>";
				echo "<b>- ".$reviews[$i]->customer. " -</b>";
				if($reviews[$i]->public == 0){
						 echo ' <span class="spanLink" onclick="publicReview(\''.$reviews[$i]->id.'\',\'1\')">Public</span>';
				 }else{
						echo ' <span class="spanLink" onclick="publicReview(\''.$reviews[$i]->id.'\',\'0\')">UnPublic</span>';
				 }
				 echo '&nbsp;&nbsp;|&nbsp;&nbsp;<span class="spanLink" onclick="deleteReview(\''.$reviews[$i]->id.'\')">Remove</span>';
			}
		}
	}
}
class VSTItem extends JObject{
	
	var $id					= null;
	var $title				= null;
	var $description		= null;
	var $fulldescription	= null;
	var $url				= null;
	var $contact_link		= null;
	var $type				= null;
	var $specification      = null;
	var $developers         = null;
	var $developer_id       = null;
	var $hit				= null;
	var $public				= 1;
	var $feature			= 0;
	var $categoryId			= 0;
	var $date_created		= null;
	var $last_modify		= null;
	
	function VSTItem($id = 0 ){
		$this->id = $id;
	}
	function bind(& $array){
		
		// Bind the array
		if (!$this->setProperties($array)) {
			$this->setError("Unable to bind array to item object");
			return false;
		}
		if($this->developer_id){
			$this->developer_id = implode( ',', $this->developer_id );
		}
		
		if (empty($this->id) || $this->id == 0){
			$now =& JFactory::getDate();
			$this->set( 'date_created', $now->toMySQL() );
			
		}else{
			$now =& JFactory::getDate();
			$this->set( 'last_modify', $now->toMySQL() );
		}
		
		
		if($this->feature != 1) $this->feature = 0;
		
		// Make sure its an integer
		$this->id = (int) $this->id;

		return true;
		
	}
	function save(){
		$db 	=& JFactory::getDBO();
		if(is_array($this->type))
			{			
				$type = implode(",", $this->type);
			}
		if($this->id != 0){
			
			$sql = "UPDATE #__vportfolio SET ".
					"title = '".mysql_escape_string($this->title)."',".
					"description = '".mysql_escape_string($this->description)."',".
					"fulldescription = '".mysql_escape_string($this->fulldescription)."',".
					"url = '".$this->url."',".
					"contact_link = '".$this->contact_link."',".
					"hit = '".$this->hit."',".
					"type = '".$type."',".
					"specification = '".mysql_escape_string($this->specification)."',".
					"developers = '".$this->developers."',".
					"developer_id = '".$this->developer_id."',".
					"public = '".$this->public."',".
					"feature = '".$this->feature."',".
					"categoryId = '".$this->categoryId."',".
					"date_created = '".$this->date_created."',".
					"last_modify = '".$this->last_modify."'".
					" WHERE id = '".$this->id."'"; 
		}else{
			$sql = "INSERT INTO #__vportfolio SET ".
					"title = '".mysql_escape_string($this->title)."',".
					"description = '".mysql_escape_string($this->description)."',".
					"fulldescription = '".mysql_escape_string($this->fulldescription)."',".
					"url = '".$this->url."',".
					"contact_link = '".$this->contact_link."',".
					"type = '".$type."',".
					"specification = '".mysql_escape_string($this->specification)."',".
					"developers = '".$this->developers."',".
					"developer_id = '".$this->developer_id."',".
					"hit = '".$this->hit."',".
					"public = '".$this->public."',".
					"feature = '".$this->feature."',".
					"categoryId = '".$this->categoryId."',".
					"date_created = '".$this->date_created."',".
					"last_modify = '".$this->last_modify."'";
			
		}
		$db->setQuery($sql);
		$return = $db->query();
		
		if($this->id == 0 )
			$this->id = $db->insertid();
		
			
		//Save image
		$path_image = JPATH_SITE."/components/com_vportfolio/images/".$this->id."/";
		
		if(!is_dir($path_image)){
			JFolder::create($path_image,755);
		}else{
			chmod($path_image,0755);
		}
		
		for($i=0;$i<sizeof($_FILES["images"]["name"]);$i++){
			if($_FILES["images"]["name"][$i] !=""){
				
				srand(time());
				$random = (rand()%99);

				$imageName = $random."_".str_replace(" ","_",$_FILES["images"]["name"][$i]);
				
				
				
				move_uploaded_file($_FILES["images"]["tmp_name"][$i],$path_image.$imageName);
				
				list($imgWidth, $imgHeight, $type, $attr) = getimagesize($path_image.$imageName);
				$imgSize = $imgWidth."x".$imgHeight;
				
				$imageTitle = $_FILES["images"]["name"][$i];
				$query = "INSERT INTO #__vportfolio_image SET ".
				"itemId = '".$this->id."',".
				"imageTitle = '".$imageTitle."',".
				"imageSize = '".$imgSize."',".
				"imageName = '".$imageName."'"
				;
				$db->setQuery($query);
				$db->query();
			}
		}
		
		return $this->id;
	}
	
}
?>
